Простое копирование свойств одного класса в другой
Редактировал(а) Alexandr Fokin 2022/12/07 07:43
//Source
ClassA a = new ClassA()
{
A = 10,
B = 20
};
//Destination
ClassB b = new ClassB();
//Source class instance parameter
var parametrB = Expression.Parameter(b.GetType());
//Destination class instance parameter
var parametrA = Expression.Parameter(a.GetType());
var copyPropertyAEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("A")),
Expression.Property(parametrA, a.GetType().GetProperty("A"))
);
var copyPropertyBEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("B")),
Expression.Property(parametrA, a.GetType().GetProperty("B"))
);
var copyPropertyEx = Expression.Block(
copyPropertyAEx,
copyPropertyBEx
);
var copyPropertyDelegate = Expression
.Lambda<Func<ClassB, ClassA, int>>(copyPropertyEx, parametrB, parametrA)
.Compile();
var result = copyPropertyDelegate.Invoke(b, a);
ClassA a = new ClassA()
{
A = 10,
B = 20
};
//Destination
ClassB b = new ClassB();
//Source class instance parameter
var parametrB = Expression.Parameter(b.GetType());
//Destination class instance parameter
var parametrA = Expression.Parameter(a.GetType());
var copyPropertyAEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("A")),
Expression.Property(parametrA, a.GetType().GetProperty("A"))
);
var copyPropertyBEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("B")),
Expression.Property(parametrA, a.GetType().GetProperty("B"))
);
var copyPropertyEx = Expression.Block(
copyPropertyAEx,
copyPropertyBEx
);
var copyPropertyDelegate = Expression
.Lambda<Func<ClassB, ClassA, int>>(copyPropertyEx, parametrB, parametrA)
.Compile();
var result = copyPropertyDelegate.Invoke(b, a);